package com.wlstock.funi.app;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Environment;
import android.util.Log;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.baidu.tts.client.SpeechError;
import com.baidu.tts.client.SpeechSynthesizer;
import com.baidu.tts.client.SpeechSynthesizerListener;
import com.em.baseapplication.BaseApplication;
import com.em.operate.util.FileUtil;
import com.maxleap.GetCallback;
import com.maxleap.MLDataManager;
import com.maxleap.MLObject;
import com.maxleap.exception.MLException;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.tencent.bugly.crashreport.CrashReport;
import com.wlstock.funi.app.FundAsyTask.TaskLitener;
import com.wlstock.funi.app.FundAsyTask.TaskResultListener;
import com.wlstock.funi.constant.AssetResConstant;
import com.wlstock.funi.constant.BaiduTTSConstants;
import com.wlstock.funi.constant.BuglyConstant;
import com.wlstock.funi.constant.SharePrefConstants;
import com.wlstock.funi.dao.DataBaseHelper;
import com.wlstock.funi.dao.SelfFundDao;
import com.wlstock.funi.dao.SelfFundSetDao;
import com.wlstock.funi.dao.StockBaseInfoDao;
import com.wlstock.funi.dao.StrategyDao;
import com.wlstock.funi.model.SelfFundSetModel;
import com.wlstock.funi.utils.NotiIdGenerator;
import com.wlstock.funi.utils.SharePreferenceUtils;
import com.wlstock.funi.utils.StockUtils;
import com.wlstock.funi.utils.TimeUtils;
import com.wlstock.funi.utils.ToastUtils;
import com.wlstock.funi.utils.TradeSetUtils;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class FundApplication extends BaseApplication implements SpeechSynthesizerListener {
	private RequestQueue mRequestQueue;
	public static String cookie;
	
	public static boolean isLogSuccess ;
	public static boolean isDebugMode;
	public static long    requestTimes;
	public static long    requestPrice;
	private static FundApplication instance;
	//存放url的cookie
	public HashMap<String, String> cookieMap;
	private DataBaseHelper dbHelper;
	private String mBaiduTTSDir;
	private SpeechSynthesizer mSpeechSynthesizer;
	private SoundPool soundPool;
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		//这种办法升级不标准
		dbHelper = DataBaseHelper.getHelper(this);
		instance = this;
		cookie = "";
		isLogSuccess = false;
		isDebugMode  = SharePreferenceUtils.getBoolSP(this, SharePrefConstants.IS_DEBUG_MODE,true);
		requestTimes = 0;
		requestPrice = 0;
		cookieMap = new HashMap<String, String>();
		initImageLoader(instance);
		
		//初始化bugly
		CrashReport.initCrashReport(getApplicationContext(), BuglyConstant.APP_ID, false);
		CrashReport.enableBugly(true);
		initBaiduTTS();
		initAllMarketCode();

		sysStrategyFromMaxleap();
//		deleteInvalidSFModels();

		testMaxLeap();
	}

	private void testMaxLeap() {
		MLDataManager.fetchInBackground(MLObject.createWithoutData("foobar", "123"),
				new GetCallback<MLObject>() {
					@Override
					public void done(MLObject mlObject, MLException e) {
						if (e != null && e.getCode() == MLException.INVALID_OBJECT_ID) {
							Log.d("MaxLeap", "SDK 成功连接到你的云端应用！");
						} else {
							Log.d("MaxLeap", "应用访问凭证不正确，请检查。");
						}
					}
				});
	}

	/**
	 * 删除无用的设置
	 */
	private void deleteInvalidSFModels() {
		List<SelfFundSetModel> invalidModels = SelfFundSetDao.getInstance(this).queryInvalidPendList(TimeUtils.getDateByDayOffset(new Date(),-3));
		SelfFundDao.getInstance(this).deleteWitnInvalidPendList(invalidModels);
	}

	private void initBaiduTTS() {
		FundAsyTask<Void, Void, Boolean> task = new FundAsyTask<Void, Void, Boolean>();
		task.backListener = new TaskLitener<Void, Boolean>() {
			@Override
			public Boolean doInBackground(Void... params) {
				//初始化百度语音环境
				initTTSEnv();
				//初始化百度语音
				boolean isSuccess =  initialTTS();
				return isSuccess;
			}
		};
		task.resultListener = new TaskResultListener<Boolean>() {

			@Override
			public void onPostResult(Boolean isSuccess) {
				if (isSuccess) {
					ToastUtils.showMiddleMsg(FundApplication.this, "百度语音初始化成功");
				}else {
					ToastUtils.showMiddleMsg(FundApplication.this, "百度语音初始化失败");
				}
				
			}
		};
		task.execute();
	}
	
	/**
	 * 初始化所有证券代码
	 */
	private boolean initAllMarketCode() {
		if (StockBaseInfoDao.getInstance(this).queryAllCount() == StockUtils.ALLSTOCK_NUMS) {
			return true;
		};
		FundAsyTask<Void, Void, Void> addBaseInfoTask = new FundAsyTask<Void, Void, Void>();
		addBaseInfoTask.backListener = new TaskLitener<Void, Void>() {
			
			@Override
			public Void doInBackground(Void... params) {
				// TODO Auto-generated method stub
				try {
					String stkAllStr = FileUtil.stream2Str(FileUtil.assetRes2Stream(getResources(), AssetResConstant.EM_BASE_DATA));
					JSONArray stkAllJSArr = new JSONArray(stkAllStr);
					StockBaseInfoDao.getInstance(FundApplication.this).addWithStkBaseInfoJSList(stkAllJSArr);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
			}
		};
		addBaseInfoTask.execute();
		return false;
	}

	private SpeechSynthesizer getSpeechSynthesizer() {
		if (mSpeechSynthesizer == null) {
			initialTTS();
		}
		return mSpeechSynthesizer;
	}

	public void speak(String speak){
		if (speak.isEmpty()||speak==null|| !SharePreferenceUtils.getBoolSP(this, TradeSetUtils.IS_VOICE_ON, false)) {
			return;
		}
		getSpeechSynthesizer().speak(speak);
	}
	
	private void initTTSEnv() {
        if (mBaiduTTSDir == null) {
            String sdcardPath = Environment.getExternalStorageDirectory().toString();
            mBaiduTTSDir = sdcardPath + "/" + BaiduTTSConstants.TTS_DIR_NAME;
        }
        FileUtil.makeDir(mBaiduTTSDir);
        
        FileUtil.copyFromAssetsToSdcard(false,getResources(), BaiduTTSConstants.SPEECH_FEMALE_MODEL_NAME, mBaiduTTSDir + "/" + BaiduTTSConstants.SPEECH_FEMALE_MODEL_NAME);
        FileUtil.copyFromAssetsToSdcard(false,getResources(), BaiduTTSConstants.SPEECH_MALE_MODEL_NAME, mBaiduTTSDir + "/" + BaiduTTSConstants.SPEECH_MALE_MODEL_NAME);
        FileUtil.copyFromAssetsToSdcard(false,getResources(), BaiduTTSConstants.TEXT_MODEL_NAME, mBaiduTTSDir + "/" + BaiduTTSConstants.TEXT_MODEL_NAME);
        FileUtil.copyFromAssetsToSdcard(false,getResources(), BaiduTTSConstants.LICENSE_FILE_NAME, mBaiduTTSDir + "/" + BaiduTTSConstants.LICENSE_FILE_NAME);
        FileUtil.copyFromAssetsToSdcard(false,getResources(), "english/" + BaiduTTSConstants.ENGLISH_SPEECH_FEMALE_MODEL_NAME, mBaiduTTSDir + "/"
                + BaiduTTSConstants.ENGLISH_SPEECH_FEMALE_MODEL_NAME);
        FileUtil.copyFromAssetsToSdcard(false,getResources(), "english/" + BaiduTTSConstants.ENGLISH_SPEECH_MALE_MODEL_NAME, mBaiduTTSDir + "/"
                + BaiduTTSConstants.ENGLISH_SPEECH_MALE_MODEL_NAME);
        FileUtil.copyFromAssetsToSdcard(false,getResources(), "english/" + BaiduTTSConstants.ENGLISH_TEXT_MODEL_NAME, mBaiduTTSDir + "/"
                + BaiduTTSConstants.ENGLISH_TEXT_MODEL_NAME);
    }

	private void sysStrategyFromMaxleap(){
		StrategyDao.getInstance(this).sysFromServer();
	}


	
	private boolean initialTTS() {
        this.mSpeechSynthesizer = SpeechSynthesizer.getInstance();
        this.mSpeechSynthesizer.setContext(this);
        this.mSpeechSynthesizer.setSpeechSynthesizerListener(this);
        // 文本模型文件路径 (离线引擎使用)
        this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_TTS_TEXT_MODEL_FILE, mBaiduTTSDir + "/"
                + BaiduTTSConstants.TEXT_MODEL_NAME);
        // 声学模型文件路径 (离线引擎使用)
        this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_TTS_SPEECH_MODEL_FILE, mBaiduTTSDir + "/"
                + BaiduTTSConstants.SPEECH_FEMALE_MODEL_NAME);
        // 本地授权文件路径,如未设置将使用默认路径.设置临时授权文件路径，LICENCE_FILE_NAME请替换成临时授权文件的实际路径，仅在使用临时license文件时需要进行设置，如果在[应用管理]中开通了离线授权，不需要设置该参数，建议将该行代码删除（离线引擎）
//        this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_TTS_LICENCE_FILE, mBaiduTTSDir + "/"
//                + BaiduTTSConstants.LICENSE_FILE_NAME);
        // 请替换为语音开发者平台上注册应用得到的App ID (离线授权)
        this.mSpeechSynthesizer.setAppId(BaiduTTSConstants.APP_ID);
        // 请替换为语音开发者平台注册应用得到的apikey和secretkey (在线授权)
        this.mSpeechSynthesizer.setApiKey(BaiduTTSConstants.API_KEY, BaiduTTSConstants.SECRET_KEY);
        // 设置在线发音人参数（还可设置其他参数）
        this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_SPEAKER, SpeechSynthesizer.SPEAKER_FEMALE);
        // 设置Mix模式的合成策略
        this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_MIX_MODE, SpeechSynthesizer.MIX_MODE_DEFAULT);
        // 授权检测接口(可以不使用，只是验证授权是否成功)
//        AuthInfo authInfo = this.mSpeechSynthesizer.auth(TtsMode.MIX);
//        // 初始化tts
//        mSpeechSynthesizer.initTts(TtsMode.MIX);
//        // 加载离线英文资源（提供离线英文合成功能）
//        int result =mSpeechSynthesizer.loadEnglishModel(mBaiduTTSDir + "/" + BaiduTTSConstants.ENGLISH_TEXT_MODEL_NAME, mBaiduTTSDir
//                        + "/" + BaiduTTSConstants.ENGLISH_SPEECH_FEMALE_MODEL_NAME);
//        return authInfo.isSuccess();
        return true;
    }
	
	
	
	public RequestQueue getRequestQueue(){
		if (mRequestQueue == null) {
			mRequestQueue = Volley.newRequestQueue(this);
		}
		return mRequestQueue;
	}
	
	public static FundApplication getInstance(){
		return instance;
	}
	
	private void initImageLoader(Context paramContext) {
		DisplayImageOptions localDisplayImageOptions = new DisplayImageOptions.Builder()
				.cacheInMemory(false).cacheOnDisc(false).build();
		ImageLoaderConfiguration localImageLoaderConfiguration = new ImageLoaderConfiguration.Builder(
				paramContext).threadPriority(3)
				.defaultDisplayImageOptions(localDisplayImageOptions)
				.denyCacheImageMultipleSizesInMemory()
				.memoryCache(new WeakMemoryCache())
				 .memoryCacheSize(2 * 1024 * 1024)  
//				.discCache(new TotalSizeLimitedDiscCache(localFile, 52428800))
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.threadPoolSize(3).build();
		ImageLoader.getInstance().init(localImageLoaderConfiguration);
	}


	/**
	 * 下面是百度tts的一些回调函数
	 */
	@Override
	public void onError(String arg0, SpeechError arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSpeechFinish(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSpeechProgressChanged(String arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSpeechStart(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSynthesizeDataArrived(String arg0, byte[] arg1, int arg2) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSynthesizeFinish(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSynthesizeStart(String arg0) {
		// TODO Auto-generated method stub
		
	}

	private SoundPool getSoundPool() {
		if (soundPool == null) {
			soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
		}
		return soundPool;
	}

	public void playSoundPool(int voiceRaw){
		soundPool = getSoundPool();
		int sourceId = soundPool.load(this, voiceRaw, 0);
		soundPool.play(sourceId, 1, 1, 0, -1, 1);
	}


	public void playSoundPool(NotiIdGenerator.GenerFrom from){
		int voiceRaw = NotiIdGenerator.getNotiRingRaw(from);
		if (voiceRaw!=-1){
			playSoundPool(voiceRaw);
		}
	}

}
